<?php

use Biz\model\brandIndex\BrandMsg;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\service\brand\BrandActivity;
use Biz\service\BrandIndex;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Biz\service\GoodsTestActivity\PushNoticeService;
use Biz\service\NewProduct\NewProductWinnerListService;
use Doraemon\model\Sysmsg;
use Doraemon\pockets\constInterface\Push\PushId;
use Doraemon\service\Push\PushService;
use Doraemon\service\User;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\Log as tLog;

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);

require_once '/data/wwwroot/g_vendor/autoload.php';

//获取活动列表数据
$field = ['id', 'basic_title', 'schedule_start_time', 'schedule_end_time', 'brand_id', 'report_num','type'];
$where['activity_state'] = FineGoodsModel::STATE_PASS;
$where['type[<]'] = FineGoodsModel::TYPE_EVALUATION;//只有轻测 以及开箱类型需要给品牌后台发送消息通知
$activityList = FineGoodsModel::selectList($where, $field);

//获取快递已签收且第7天内仍未产出内容
$joinedField = ['uid', 'join_status', 'logistics_status', 'delivered_time', 'fine_goods_id'];
$joinedWhere['delivered_time[>=]'] = time() - FineGoodsJoinModel::DELIVERED_TIME;
$joinedList = FineGoodsJoinModel::select($joinedField, $joinedWhere);
try {
    $now = time();
    if ($joinedList) {
        $uidArr = array_column($joinedList, 'uid') ?? [];
        $fineGoodsId = array_column($joinedList, 'fine_goods_id') ?? [];
        $userInfos = User::getBrandCards($uidArr, 0);
        $countContentMap = FineGoodsService::getCountContentsByUidArr($uidArr);
        $activityMap = NewProductWinnerListService::handleData(
            FineGoodsModel::selectList(['id' => $fineGoodsId], ['activity_title', 'id','type']),
            'id',
        );
        foreach ($joinedList as $value) {
            $contentNum = $countContentMap[$value['uid']] ?? 0;
            $activityTitle = $activityMap[$value['fine_goods_id']]['activity_title'] ?? '';
            $activityTypeName = FineGoodsModel::TYPE_MAP[$activityMap[$value['fine_goods_id']]['type']] ?? '';
            //快递已签收且第6天内仍未产出内容 消息通知
            if (date('Ymd', $value['delivered_time'] + FineGoodsJoinModel::DELIVERED_TIME_PUSH_SIX) == date('Ymd',
                    $now) && $contentNum == 0) {
                PushNoticeService::pushSysMsg($value['uid'],
                    "{$activityTypeName}活动即将到期",
                    "你参与的「" . $activityTitle . "」{$activityTypeName}活动即将到期，请尽快提交{$activityTypeName}报告。逾期未发布内容将影响后续好好测活动资格。",
                    User::HAOHAOZHUFULIGUAN_UID,
                    Sysmsg::TYPE_NOTICE,
                    $value['fine_goods_id']
                );
                tLog::info('Notification.php',
                    ['message' => '快递已签收且第6天内仍未产出内容 消息通知' . '活动名称：' . $activityTitle . '活动id:' . $value['fine_goods_id'] . PHP_EOL]);

                echo '快递已签收且第6天内仍未产出内容 消息通知' . '活动名称：' . $activityTitle . '活动id:' . $value['fine_goods_id'] . PHP_EOL;

                //好物轻测-获选用户报告生产提醒机器人
                pushWeChatMsg($activityTitle, $userInfos[$value['uid']]['nick'],
                    $value['uid'], $value['delivered_time'], $value['fine_goods_id']);
                echo '获选用户报告生产提醒' . '活动名称：' . $activityTitle . '活动id:' . $value['fine_goods_id'] . PHP_EOL;
            }

            //快递已签收且第7天内仍未产出内容 发送push
            if (date('Ymd', $value['delivered_time'] + FineGoodsJoinModel::DELIVERED_TIME_PUSH) == date('Ymd',
                    $now) && $contentNum == 0) {
                $nickName = $userInfos[$value['uid']]['nick'] ?? '';
                pushMsg($value['uid'], $value['fine_goods_id'],'',$activityTypeName);
                tLog::info('Notification.php',
                    ['message' => '快递已签收且第7天内仍未产出内容 发送push' . '用户昵称：' . $nickName . '用户uid:' . $value['uid'] . '活动id' . $value['fine_goods_id'] . PHP_EOL]);

                echo '快递已签收且第7天内仍未产出内容 发送push' . '用户昵称：' . $nickName . '用户uid:' . $value['uid'] . '活动id' . $value['fine_goods_id'] . PHP_EOL;
            }

        }
    }
    if ($activityList) {
        foreach ($activityList as $item) {
            $activityName = FineGoodsModel::TYPE_MAP_BACKUPS[$item['type']];
            //活动申请中	品牌后台通知	你所提报的 瓦力扫地机柜 好物轻测活动已上线，住友申请中。
            if (date('Ymd', $item['schedule_start_time']) == date('Ymd', $now)) {
                $msg = "你所提报的 %s {$activityName}活动已上线，住友申请中。";
                $msg = sprintf($msg, $item['basic_title']);
                BrandIndex::writeMsg($item['brand_id'], BrandMsg::MSG_TYPE_OVER,
                    BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
                echo $msg.PHP_EOL.'brand_id:'.$item['brand_id'].',fine_goods_id:'.$item['id'].PHP_EOL;
            }

            //名单审核中    品牌后台通知	你所提报的 瓦力扫地机柜 好物轻测活动申请时间已结束，名单正在审核中。
            if (date('Ymd', $item['schedule_end_time'] + FineGoodsModel::ONE_DAY) == date('Ymd', $now)) {
                $msg = "你所提报的 %s {$activityName}活动申请时间已结束，名单正在审核中。";
                $msg = sprintf($msg, $item['basic_title']);
                BrandIndex::writeMsg($item['brand_id'], BrandMsg::MSG_TYPE_OVER,
                    BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
                echo $msg.PHP_EOL.'brand_id:'.$item['brand_id'].',fine_goods_id:'.$item['id'].PHP_EOL;
            }

            //快递需寄出	品牌后台通知	你所提报的 瓦力扫地机柜 好物轻测活动获选名单已选出，请及时发货并填报物流信息。
            if (date('Ymd',
                    ($item['schedule_end_time'] + FineGoodsModel::VERIFY_USER_TIME + FineGoodsModel::ONE_DAY)) == date('Ymd',
                    $now)) {
                $msg = "你所提报的 %s {$activityName}活动获选名单已选出，请及时发货并填报物流信息。";
                $msg = sprintf($msg, $item['basic_title']);
                BrandIndex::writeMsg($item['brand_id'], BrandMsg::MSG_TYPE_OVER,
                    BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
                echo $msg.PHP_EOL.'brand_id:'.$item['brand_id'].',fine_goods_id:'.$item['id'].PHP_EOL;
            }
        }
    }


} catch (Exception $exception) {
    tLog::error('error', $exception->getMessage());
}

/**
 * 发送push通知
 * @param $uid
 * @param $activityId
 * @param string $title
 * @param $activityTypeName
 * @throws \JsonException
 */
function pushMsg($uid, $activityId, string $title = '' , $activityTypeName)
{
    $link = BrandActivity::getFindGoodsTestLink($activityId);
    $link = LinkFormat::encryptionLink($link);
    $activityTitle = FineGoodsModel::get('activity_title', ['id' => $activityId]);
    $pushId = PushId::BRAND_GOODS_TEST_PUSH . date('Y-m-d');
    $params = [
        'uid' => $uid,
        'title' => $title,
        'alert' => '你参与的「' . $activityTitle . "」{$activityTypeName}活动已到期，请尽快提交{$activityTypeName}报告。",
        'param' => [
            'push_id' => $pushId,
            'link' => $link,
        ],
    ];
    $res = PushService::send($params);
    tLog::info('Notification.php-pushMsg', ['$params' => $params, 'res' => $res]);
}

function pushWeChatMsg($activityName, $nick, $uid, $date, $fineGoodsId)
{
    //钉钉机器人消息通知
    \Doraemon\service\DingTalkAlert::sendTextMsg(\Doraemon\service\DingTalkAlert::ROBOT_FINE_GOODS_TEST,
        implode("\n", [
            "活动 ID：" . $fineGoodsId,
            "活动名称：" . $activityName,
            "获选人：" . $nick . "-uid:" . $uid,
            "签收日期：" . date('Y-m-d H:i:s', $date),
            "报告最晚提交时间：" . date('Y-m-d', $date + FineGoodsJoinModel::DELIVERED_TIME_PUSH),
            "请及时审核。",
        ])
        , false, ['qiyue']);
    tLog::info('Notification.pushWeChatMsg',
        ['activityName' => $activityName, 'nick' => $nick, 'uid' => $uid, 'date' => date('Y-m-d H:i:s', $date)]);
}